package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.Coupon;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.domain.UserCoupon;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.CouponService;
import com.ruitaowang.goods.service.UserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class APIUserCouponController extends BaseController{

    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private CouponService couponService;
    /**
     * @api {get} /api/wap/userCoupon 个人领取优惠券-查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon
     *
     * @apiName list
     * @apiGroup userCoupon
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {byte} couponType 优惠券 类别.
     * @apiParam {long} couponTime 优惠券 时间.
     * @apiParam {String} endTime 优惠券使用结束时间.
     * @apiParam {byte} overdueRstatus 优惠券过期状态.
     * @apiParam {int} percentage 优惠折扣.
     * @apiParam {int} reach1 满.
     * @apiParam {int} score1 返.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "percentage":0,
     *                   "companyId":0,
     *                   "couponType":0,
     *                   "couponTime":0,
     *                   "endTime":"",
     *                   "overdueRstatus":0,
     *                   "reach1":0,
     *                   "score1":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon"
     *  }
     */
    @RequestMapping("/api/wap/userCoupon")
    public String list(UserCoupon userCoupon) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userCoupon.setUserId(user.getId());
        userCoupon.setCouponType((byte)0);
        MsgOut o = MsgOut.success(userCouponService.select(userCoupon));
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/userCoupon/page 个人领取优惠券-(分页)查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon/page
     *
     * @apiName listForPage
     * @apiGroup userCoupon
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {byte} couponType 优惠券 类别.
     * @apiParam {long} couponTime 优惠券 时间.
     * @apiParam {String} endTime 优惠券使用结束时间.
     * @apiParam {byte} overdueRstatus 优惠券过期状态.
     * @apiParam {int} percentage 优惠折扣.
     * @apiParam {int} reach1 满.
     * @apiParam {int} score1 返.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "percentage":0,
     *                   "companyId":0,
     *                   "couponType":0,
     *                   "couponTime":0,
     *                   "endTime":"",
     *                   "overdueRstatus":0,
     *                   "reach1":0,
     *                   "score1":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon/page"
     *  }
     */
    @RequestMapping("/api/wap/userCoupon/page")
    public String listForPage(UserCoupon userCoupon, int page) {
        userCoupon.setPage(page);
        if (!ObjectUtils.isEmpty(userCoupon.getSidx())) {
            userCoupon.setOrderBy(userCoupon.getSidx() + " " + userCoupon.getSord() + "," + userCoupon.getOrderBy());
        }
        List<UserCoupon> couponList=new ArrayList<>();
        //调取正常状态的券
        userCoupon.setOverdueRstatus((byte)0);
        List<UserCoupon> userCoupons=userCouponService.selectForPage(userCoupon);
        //检测过期的券 更新过期   返回正确数据
        for (UserCoupon uc:userCoupons){
            if (Long.parseLong(uc.getEndTime()) < System.currentTimeMillis()){
                uc.setOverdueRstatus((byte)1);
                   userCouponService.update(uc);
            }else {
                couponList.add(uc);
            }
        }
        MsgOut o = MsgOut.success(couponList);
        o.setRecords(userCoupon.getRecords());
        o.setTotal(userCoupon.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {post} /api/wap/userCoupon 个人领取优惠券-创建
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon
     *
     * @apiName create
     * @apiGroup userCoupon
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {byte} couponType 优惠券 类别.
     * @apiParam {long} couponTime 优惠券 时间.
     * @apiParam {String} endTime 优惠券使用结束时间.
     * @apiParam {byte} overdueRstatus 优惠券过期状态.
     * @apiParam {int} percentage 优惠折扣.
     * @apiParam {int} reach1 满.
     * @apiParam {int} score1 返.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "percentage":0,
     *                   "companyId":0,
     *                   "couponType":0,
     *                   "couponTime":0,
     *                   "endTime":"",
     *                   "overdueRstatus":0,
     *                   "reach1":0,
     *                   "score1":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon"
     *  }
     */
    @RequestMapping(value = "/api/wap/userCoupon", method = RequestMethod.POST)
    public String create(UserCoupon userCoupon) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(userCoupon)){
            return this.renderJson(MsgOut.error("Plz login."));
        }

        UserCoupon uc=new UserCoupon();
        uc.setUserId(user.getId());
        uc.setCouponId(userCoupon.getCouponId());
        List<UserCoupon> userCoupons=userCouponService.select(userCoupon);
        if (!ObjectUtils.isEmpty(userCoupons)){
            if (userCoupons.get(0).getOverdueRstatus() == 0 && Long.parseLong(userCoupons.get(0).getEndTime()) >= System.currentTimeMillis()){
                return this.renderJson(MsgOut.error("您已领取该优惠券 切勿重复领取"));
            }else {
                UserCoupon updateUC=userCoupons.get(0);
                updateUC.setOverdueRstatus((byte)1);
                userCouponService.update(updateUC);
            }
        }
        Coupon coupon=couponService.selectByPK(userCoupon.getId());
        if (!ObjectUtils.isEmpty(coupon)){
            UserCoupon newUc=new UserCoupon();
            newUc.setCouponId(coupon.getId());
            newUc.setUserId(user.getId());
            newUc.setCouponType(coupon.getCouponType());
            newUc.setCompanyId(coupon.getCompanyId());
            newUc.setGoodsId(coupon.getGoodsId());
            newUc.setCouponTime(coupon.getCouponTime());
            newUc.setEndTime(coupon.getCouponEndtime().toString());
            newUc.setPercentage(coupon.getPercentage());
            newUc.setReach1(coupon.getReach1());
            newUc.setScore1(coupon.getScore1());
            userCouponService.insert(newUc);
        }
        MsgOut o = MsgOut.success(userCoupon);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/wap/userCoupon 个人领取优惠券-修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon
     *
     * @apiName update
     * @apiGroup userCoupon
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {byte} couponType 优惠券 类别.
     * @apiParam {long} couponTime 优惠券 时间.
     * @apiParam {String} endTime 优惠券使用结束时间.
     * @apiParam {byte} overdueRstatus 优惠券过期状态.
     * @apiParam {int} percentage 优惠折扣.
     * @apiParam {int} reach1 满.
     * @apiParam {int} score1 返.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "percentage":0,
     *                   "companyId":0,
     *                   "couponType":0,
     *                   "couponTime":0,
     *                   "endTime":"",
     *                   "overdueRstatus":0,
     *                   "reach1":0,
     *                   "score1":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon"
     *  }
     */
    @RequestMapping(value = "/api/wap/userCoupon", method = RequestMethod.PUT)
    public String update(UserCoupon userCoupon) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userCouponService.update(userCoupon);
        MsgOut o = MsgOut.success(userCoupon);
        return this.renderJson(o);
    }
    /**
     * @api {delete} /api/wap/userCoupon/{id} 个人领取优惠券-删除
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon/{id}
     *
     * @apiName delete
     * @apiGroup userCoupon
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/userCoupon/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(userCouponService.delete(id));
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/userCoupon/{id} 个人领取优惠券-单个查询
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/userCoupon/{id}
     *
     * @apiName findCommentId
     * @apiGroup userCoupon
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "percentage":0,
     *                   "companyId":0,
     *                   "couponType":0,
     *                   "couponTime":0,
     *                   "endTime":"",
     *                   "overdueRstatus":0,
     *                   "reach1":0,
     *                   "score1":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/userCoupon/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/userCoupon/{id}", method = RequestMethod.GET)
    public String findCommentId(@PathVariable("id")Long  id) {
        MsgOut o = MsgOut.success(userCouponService.selectByPK(id));
        return this.renderJson(o);
    }
}
